package com.distributer.order.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import com.alibaba.fastjson.JSONObject;
import com.distributer.order.controller.dto.OrderReqInfo;
import com.distributer.order.event.OrderCreateEvent;
import com.distributer.order.mapper.OrderMapper;
import com.distributer.order.model.Order;
import com.distributer.order.service.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private ApplicationContext applicationContext;
	@Autowired
	private JedisPool jedisPool;

	@Override
	public String addOrder(OrderReqInfo orderReqInfo) {
		Order order = new Order(orderReqInfo.getProductInfo(), orderReqInfo.getInsuranceInfo());
		orderMapper.insert(order);
		applicationContext.publishEvent(new OrderCreateEvent(order));
		return order.getOrderNo();
	}

	@Override
	public void updateOrder(Order order) {
		orderMapper.update(order);
	}

	@Override
	public Order findOrderByOrderNo(String orderNo) {
		return orderMapper.queryOrderByOrderNo(orderNo);
	}

	@Override
	public Order findOrderFromCacheByOrderNo(String orderNo) {
		Jedis jedis = jedisPool.getResource();
		Order order = null;
		try {
			String orderSource = jedis.get(orderNo);
			if (StringUtils.isEmpty(orderSource)) {
				return order;
			}
			order = JSONObject.parseObject(orderSource, Order.class);
		} finally {
			jedis.close();
		}
		return order;
	}
	
	@Override
	public void refreshOrderToCache(Order order) {
		Jedis jedis = jedisPool.getResource();
		try{
			jedis.set(order.getOrderNo(), JSONObject.toJSONString(order));
		}finally{
			jedis.close();
		}
	}
	
	@Override
	public void removeOrderFromCache(String orderNo) {
		Jedis jedis = jedisPool.getResource();
		try{
			jedis.del(orderNo);
		}finally{
			jedis.close();
		}
	}

	@Override
	public void updateOrderStatusByOrderItemCreateResult(String orderNo, boolean orderItemCreateResult) {
		int orderStatus = Order.getOrderStatusByOrderItemCreateResult(orderItemCreateResult);
		orderMapper.updateOrderStatusByOrderItemCreateResult(orderNo, orderStatus);
	}
}
